<?php

namespace app\games\controller;

use think\Controller;
use think\Request;

class Order extends Controller
{
    protected $OrderModel;
    protected $UserModel;
    public function _initialize()
    {
        parent::_initialize();
        $this->OrderModel = model('common/Games/Gameorder');
        $this->UserModel = model('common/Games/Gameuser');
    }

    // 添加订单信息
    public function addorder()
    {
        $gameuserid = $this->request->param('id', 0, 'trim');
        $wxcode = $this->request->param('wxcode', '', 'trim');
        $auto = $this->request->param('auto', 0, 'trim');

        $user = $this->UserModel->find($gameuserid);
        if (!$user) {
            $this->error('用户不存在');
        }

        $order = $this->OrderModel->where('wxcode', $wxcode)->find();
        if ($order) {
            $this->error('订单已存在');
        }

        $data = [
            'gameuserid' => $gameuserid,
            'wxcode' => $wxcode,
            'auto' => $auto,
        ];

        $res = $this->OrderModel->save($data);
        if (!$res) {
            $this->error($this->OrderModel->getError());
        } else {
            $this->success('添加成功');
        }
    }

    // 获取消费订单
    public function getorder()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0, 'trim');

            $order = $this->OrderModel->where('gameuserid', $id)->select();

            if ($order) {
                $this->success('获取成功', null, $order);
            } else {
                $this->error('暂无订单');
            }
        }
    }

    // 删除订单
    public function delorder()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id', 0, 'trim');

            $res = $this->OrderModel->where('id', $id)->find();

            if (!$res) {
                $this->error('订单不存在');
            }

            $del = $this->OrderModel->where('id', $id)->delete();

            if ($del) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
    }
}
